<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 17-11-3
 * Time: 下午7:32
 */
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'0.0.0.0',4481);
socket_listen($socket);

$connArr = [$socket];

$r = $connArr;
$w = null;
$e = null;

var_dump($r);
socket_set_nonblock($socket);

while(true){
    $r = $connArr;
    $ready = socket_select($r,$w,$e,null);

    if($ready === false){
        die("error");
    }else if($ready < 1){
        continue;
    }

    var_dump($r);
    foreach($r as $read){
        if($read == $socket){
            //有新的链接进入
            $conn = socket_accept($socket);
            socket_set_nonblock($conn);
            echo 'new conn:';
            var_dump($conn);
            echo PHP_EOL;

            $connArr[] = $conn;
        }else{
            echo 'new data:';
            //链接有数据进入
            $msg = socket_read($read,1024);
            echo $msg,PHP_EOL;
            socket_write($read,'server: '.$msg);

            foreach($connArr as $write){
                if($write == $socket){

                }else if($write == $read){

                }else{
                    socket_write($write,'server: '.$msg);
                }
            }
        }
    }
}

foreach($connArr as $key=>$c){
    socket_close($c);
    unset($connArr[$key]);
}